#!/usr/bin/env python
# -*- coding:utf-8 -*-

# file:homework9_4.py
# author:wmf
# datetime:2021/5/19 20:37
# software: PyCharm
'''
this is function description
'''
# import module your need

# 4 设计一款能实现多人聊天的系统：使用socket和多线程技术，编写全多人聊天室；
import socket
import sys
import threading


class ChatSever:
    def __init__(self):
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.addr = ('127.0.0.1', 8888)
        self.users = {}

    def start_sever(self):
        try:
            self.sock.bind(self.addr)
        except Exception as e:
            print(e)
        self.sock.listen(5)
        print("服务器已开启,等待连接中...")
        print("输入stop sever关闭服务器")

        self.accept_cont()

    def accept_cont(self):
        while True:
            s, addr = self.sock.accept()
            self.users[addr] = s
            number = len(self.users)
            print("用户%s已连接,现有%d位用户" % (addr, number))

            threading.Thread(target=self.recv_send, args=(s, addr)).start()

    def recv_send(self, sock, addr):
        while True:
            try:
                response = sock.recv(4096).decode("gbk")
                msg = "用户{}发来消息:{}".format(addr, response)

                for client in self.users.values():
                    client.send(msg.encode("gbk"))
            except (ConnectionResetError, ConnectionAbortedError):
                print("用户{}已退出".format(addr))
                self.users.pop(addr)
                break

    def close_sever(self):
        for client in self.users.values():
            client.close()
        self.sock.close()
        sys.exit(0)


if __name__ == "__main__":
    sever = ChatSever()
    t1 = threading.Thread(target=sever.start_sever,daemon=True)
    t1.start()

    while True:
        cmd = input()
        if cmd == "stop sever":
            sever.close_sever()
            break
        else:
            print("请重新输入关闭服务器指令")
